document.addEventListener('DOMContentLoaded', function() {
    // 立即开始获取认证token
    getAuthToken();
});

let authToken = null;

// 分离token获取逻辑
async function getAuthToken() {
    try {
        const response = await fetch('/api/auth/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: 'admin',
                password: '123456'
            }),
            credentials: 'include'
        });

        if (!response.ok) {
            throw new Error('认证失败');
        }

        const data = await response.json();
        authToken = data.token;
        
        // 获取到token后立即加载标签
        loadTags();
    } catch (error) {
        console.error('认证错误:', error);
    }
}

async function loadTags() {
    try {
        const tagList = document.getElementById('tagList');
        if (!tagList) return;

        const canEdit = tagList.dataset.canEdit === 'true';
        const isAdmin = tagList.dataset.isAdmin === 'true';

        const response = await fetch('/api/tags', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });

        if (!response.ok) {
            throw new Error('加载标签失败');
        }

        const tags = await response.json();
        
        // 清除加载动画
        tagList.innerHTML = '';
        
        const fragment = document.createDocumentFragment();
        
        tags.forEach(tag => {
            const tagElement = document.createElement('div');
            tagElement.className = `tag-item ${!canEdit ? 'readonly' : ''} ${isAdmin ? 'admin' : ''}`;
            tagElement.textContent = tag.name;
            
            if (canEdit || isAdmin) {
                tagElement.onclick = () => selectTag(tag);
            }
            
            fragment.appendChild(tagElement);
        });

        tagList.appendChild(fragment);
    } catch (error) {
        console.error('加载标签失败:', error);
        // 发生错误时也要清除加载动画
        const tagList = document.getElementById('tagList');
        if (tagList) {
            tagList.innerHTML = '<div class="layui-text" style="color: #FF5722;">加载失败: ' + error.message + '</div>';
        }
    }
}

function selectTag(tag) {
    window.parent.postMessage({
        type: 'tagSelected',
        tag: tag
    }, '*');
}